<template>
  <div class="hunt-container">
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-input
        v-model="searchQuery"
        placeholder="请输入商品名称"
        class="search-input"
        @keyup.enter.native="performSearch"
      >
      </el-input>
      <el-button 
        type="primary" 
        icon="el-icon-search" 
        @click="performSearch"
        class="search-button"
      >
        搜索
      </el-button>
    </div>
    
    <!-- 分类筛选 -->
    <div class="category-section">
      <el-radio-group v-model="selectedCategory" @change="filterByCategory">
        <el-radio-button label="">全部</el-radio-button>
        <el-radio-button
          v-for="category in categories"
          :key="category.categoryId"
          :label="category.categoryId"
        >
          {{ category.categoryName }}
        </el-radio-button>
      </el-radio-group>
    </div>

    <!-- 搜索结果展示 -->
    <div class="results-section">
      <!-- 无结果提示 -->
      <div v-if="searchPerformed && filteredResults.length === 0" class="no-results">
        <el-empty description="没有找到相关商品"></el-empty>
      </div>
      
      <!-- 商品卡片展示 -->
      <div v-else class="product-grid">
        <el-row :gutter="20">
          <el-col 
            v-for="(product, index) in filteredResults" 
            :key="index" 
            :xs="12" :sm="6" :md="6" :lg="6"
          >
            <el-card 
              class="product-card" 
              shadow="hover"
              @click.native="viewProductDetail(product)"
            >
              <div class="card-image">
                <img :src="product.imageUrl || 'https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png'" 
                     alt="商品图片">
              </div>
              <div class="card-content">
                <h3 class="product-name">{{ product.productName }}</h3>
                <p class="price">¥{{ product.price }}</p>
                <p class="description">{{ product.description }}</p>
              </div>
            </el-card>
          </el-col>
        </el-row>
        
        <!-- 分页 -->
        <div class="pagination" v-if="filteredResults.length > 0">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[12, 24, 36, 48]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalItems">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import productApi from '@/api/product';

export default {
  name: 'HuntFor',
  data() {
    return {
      searchQuery: '',
      searchResults: [],
      filteredResults: [],
      searchPerformed: false,
      categories: [],
      selectedCategory: '',
      currentPage: 1,
      pageSize: 12,
      totalItems: 0
    };
  },
  created() {
    this.fetchCategories();
  },
  methods: {
    async fetchCategories() {
      try {
        const response = await productApi.getAllCategories();
        this.categories = response.data || [];
      } catch (error) {
        console.error('获取分类失败:', error);
        this.$message.error('获取分类失败');
      }
    },
    
    async performSearch() {
      try {
        const params = {
          keyword: this.searchQuery,
          page: this.currentPage,
          size: this.pageSize
        };
        
        const response = await productApi.searchProducts(params);
        this.searchResults = response.data || [];
        this.filteredResults = [...this.searchResults];
        this.totalItems = response.total || 0;
        this.searchPerformed = true;
      } catch (error) {
        console.error('搜索失败:', error);
        this.$message.error('搜索失败');
        this.searchResults = [];
        this.filteredResults = [];
        this.searchPerformed = true;
      }
    },
    
    filterByCategory() {
      if (!this.selectedCategory) {
        this.filteredResults = [...this.searchResults];
      } else {
        this.filteredResults = this.searchResults.filter(
          product => product.categoryId === this.selectedCategory
        );
      }
      this.currentPage = 1;
      this.totalItems = this.filteredResults.length;
    },
    
    viewProductDetail(product) {
      this.$router.push({ name: 'productDetail', query: { productId: product.productId } });
    },
    
    handleSizeChange(val) {
      this.pageSize = val;
      this.performSearch();
    },
    
    handleCurrentChange(val) {
      this.currentPage = val;
      this.performSearch();
    }
  }
};
</script>

<style scoped>
.hunt-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.search-section {
  display: flex;
  margin-bottom: 20px;
  align-items: center;
}

.search-input {
  flex: 1;
  margin-right: 10px;
}

.search-button {
  width: 100px;
}

.category-section {
  margin-bottom: 20px;
}

.category-section .el-radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.category-section .el-radio-button {
  margin-right: 0;
}

.results-section {
  margin-top: 20px;
}

.product-grid {
  margin-top: 20px;
}

/* 调整卡片间距 */
.el-row {
  margin-left: -10px !important;
  margin-right: -10px !important;
}

.el-col {
  padding-left: 10px !important;
  padding-right: 10px !important;
  margin-bottom: 20px;
}

/* 卡片整体样式 */
.product-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease;
  border-radius: 8px !important;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
  cursor: pointer;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px 0 rgba(0, 0, 0, 0.12);
}

/* 卡片图片区域 */
.card-image {
  width: 100%;
  padding-top: 100%; /* 正方形比例 */
  position: relative;
  overflow: hidden;
  background-color: #f8f8f8;
  border-radius: 8px 8px 0 0;
}

.card-image img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.product-card:hover .card-image img {
  transform: scale(1.05);
}

/* 卡片内容区域 */
.card-content {
  padding: 15px;
  flex: 1;
  background: #fff;
}

.product-name {
  margin: 0 0 10px;
  font-size: 16px;
  font-weight: bold;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #333;
  transition: color 0.3s;
}

.product-card:hover .product-name {
  color: #409EFF;
}

.price {
  color: #f56c6c;
  font-weight: bold;
  margin: 10px 0;
  font-size: 18px;
}

.description {
  color: #666;
  font-size: 14px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 10px;
  line-height: 1.5;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

.no-results {
  margin-top: 50px;
  text-align: center;
}

@media (max-width: 768px) {
  .search-section {
    flex-direction: column;
  }
  
  .search-input {
    width: 100%;
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .search-button {
    width: 100%;
  }
  
  .category-section .el-radio-group {
    flex-direction: column;
    gap: 5px;
  }
  
  .el-col {
    margin-bottom: 15px;
  }
}
</style>